﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using CoreEx.Database.Client;
using CoreEx.Database.Metadata;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.Database.MetaData.Implementation
{
    [Factory(typeof(ITypeMappingRepository))]
    public class MappingRepositoryFactory : IFactory<ITypeMappingRepository>
    {
        private static readonly IDictionary<string, ITypeMappingRepository> _repositories
          = new Dictionary<string, ITypeMappingRepository>();


        public ITypeMappingRepository CreateInstance(IFactoryRequest request)
        {
            lock (_repositories)
            {
                var repositoryName = request.ServiceName;

                if (string.IsNullOrEmpty(repositoryName))
                    repositoryName = request.Container.GetService<IConnectionInfo>().Name;


                if (!_repositories.ContainsKey(repositoryName))
                    _repositories.Add(repositoryName, new TypeMappingRepository(repositoryName));

                return _repositories[repositoryName];
            }
        }
    }
}
